package models

import (
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	"kop/libs/redis"
	"kop/modules/guild/configuration"
	"kop/modules/guild/entity"
	"kop/util/date"
	"time"
)

func GetBosses(dB *gorm.DB, guildID, guildLevel int32) []entity.Boss {

	var data []entity.Boss
	if err := dB.Where(entity.Boss{GuildID: guildID}).Find(&data).Error; err != nil {
		panic(err)
	}

	var year, month, day = time.Now().Date()

	for k, boss := range data {

		var bossYear, bossMonth, bossDay = boss.UpdatedAt.Date()
		if boss.Open && (bossYear != year || bossMonth != month || bossDay != day) {

			boss.Reset()
			dB.Save(&boss)
			data[k] = boss
		}
	}

	for _, conf := range configuration.GuildBossConfigs {

		if guildLevel >= conf.GuildLevel {

			var find = false
			for _, boss := range data {
				if boss.BossID == conf.BossID {
					find = true
				}
			}

			if !find {

				var boss = entity.Boss{GuildID: guildID, BossID: conf.BossID}
				boss.Reset()

				if err := dB.Create(&boss).Error; err == nil {
					data = append(data, boss)
				}
			}
		}
	}

	return data
}

func GetBoss(dB *gorm.DB, guildID, bossID int32) (entity.Boss, error) {

	var boss entity.Boss
	var err = dB.Where(entity.Boss{GuildID: guildID, BossID: bossID}).First(&boss).Error
	if err == nil {

		var year, month, day = time.Now().Date()
		var bossYear, bossMonth, bossDay = boss.UpdatedAt.Date()
		if boss.Open && !(bossYear == year && bossMonth == month && bossDay == day) {

			boss.Open = false
			boss.HP = 0
		}
	}

	return boss, err
}

func SaveBoss(dB *gorm.DB, boss *entity.Boss) error {

	return dB.Save(boss).Error
}

//func CreateBosses(dB *gorm.DB, guildID, level int32) error {
//
//	for _, conf := range configuration.GuildBossConfigs {
//		if conf.GuildLevel == level {
//
//			var boss = entity.GuildBoss{
//				GuildID: guildID,
//				BossID:  conf.ID,
//				HP:      conf.BossHP,
//				Open:    false,
//			}
//
//			if err := dB.Create(&boss).Error; err != nil {
//				return err
//			}
//		}
//	}
//	return nil
//}

func GetBossCaptainIDs(roleID int32) map[int32]int32 {

	var res = make(map[int32]int32)

	if b, _ := redis.Get(fmt.Sprintf("GuildBossIDs%d", roleID)); b != nil {
		_ = json.Unmarshal(b, &res)
	}

	return res
}

func SetBossCaptainIDs(roleID int32, data map[int32]int32) {

	var b, _ = json.Marshal(data)
	if err := redis.Set(fmt.Sprintf("GuildBossIDs%d", roleID), b, date.TodayExpire()); err != nil {
		panic(err)
	}
}
